package com.yunkeji.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yunkeji.common.constant.Constants;
import com.yunkeji.common.constant.UserConstants;
import com.yunkeji.common.utils.StreamUtils;
import com.yunkeji.common.utils.StringUtils;
import com.yunkeji.common.utils.TreeBuildUtils;
import com.yunkeji.dao.domain.broker.BrokerMenu;
import com.yunkeji.dao.domain.broker.BrokerUser;
import com.yunkeji.dao.domain.broker.BrokerUserMenu;
import com.yunkeji.dao.domain.sys.SysMenu;
import com.yunkeji.dao.mapper.broker.BrokerMenuMapper;
import com.yunkeji.dao.mapper.broker.BrokerUserMapper;
import com.yunkeji.dao.mapper.broker.BrokerUserMenuMapper;
import com.yunkeji.dao.vo.MetaVo;
import com.yunkeji.dao.vo.RouterVo;
import com.yunkeji.system.service.IBrokerMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 菜单 业务层处理
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class BrokerMenuServiceImpl implements IBrokerMenuService {

    private final BrokerMenuMapper baseMapper;
    private final BrokerUserMenuMapper userMenuMapper;
    private final BrokerUserMapper userMapper;

    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<BrokerMenu> selectMenuList(Long userId) {
        List<BrokerUserMenu> userMenus = userMenuMapper.selectList(Wrappers.lambdaQuery(BrokerUserMenu.class)
            .eq(BrokerUserMenu::getUserId, userId));
        if(ObjectUtil.isNull(userMenus) || userMenus.isEmpty()){
            return new ArrayList<>();
        }
        List<Long> menuIds = new ArrayList<>(userMenus.size());
        userMenus.forEach(userMenu -> menuIds.add(userMenu.getMenuId()));
        return baseMapper.selectList(new LambdaQueryWrapper<BrokerMenu>()
                .in(BrokerMenu::getMenuId, menuIds)
                .orderByAsc(BrokerMenu::getParentId)
                .orderByAsc(BrokerMenu::getOrderNum));
    }

    /**
     * 查询系统菜单列表
     *
     * @return 菜单列表
     */
    @Override
    public List<BrokerMenu> selectMenuList() {
        return baseMapper.selectList(new LambdaQueryWrapper<BrokerMenu>()
                .orderByAsc(BrokerMenu::getParentId)
                .orderByAsc(BrokerMenu::getOrderNum));
    }
    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<BrokerMenu> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (BrokerMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQueryParam());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<BrokerMenu> cMenus = menu.getChildren();
            if (CollUtil.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQueryParam());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Tree<Long>> buildMenuTreeSelect(List<SysMenu> menus) {
        if (CollUtil.isEmpty(menus)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(menus, (menu, tree) ->
            tree.setId(menu.getMenuId())
                .setParentId(menu.getParentId())
                .setName(menu.getMenuName())
                .setWeight(menu.getOrderNum()));
    }


    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(BrokerMenu menu) {
        int result = baseMapper.insert(menu);
        List<BrokerUser> users = userMapper.selectList(Wrappers.lambdaQuery(BrokerUser.class)
            .eq(BrokerUser::getDelFlag, 0));
        if(ObjectUtil.isNull(users) || users.isEmpty()){
            return result;
        }
        List<BrokerUserMenu> userMenus = new ArrayList<>(users.size());
        users.forEach(user -> {
            BrokerUserMenu userMenu = new BrokerUserMenu();
            userMenu.setMenuId(menu.getMenuId());
            userMenu.setUserId(user.getUserId());
            userMenus.add(userMenu);
        });
        userMenuMapper.insertBatch(userMenus);
        return result;
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(BrokerMenu menu) {
        return baseMapper.updateById(menu);
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Long menuId) {
        return baseMapper.deleteById(menuId);
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(BrokerMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(BrokerMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
            && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(BrokerMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(BrokerMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
            && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(BrokerMenu menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(BrokerMenu menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<BrokerMenu> getChildPerms(List<BrokerMenu> list, int parentId) {
        List<BrokerMenu> returnList = new ArrayList<>();
        for (BrokerMenu t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<BrokerMenu> list, BrokerMenu t) {
        // 得到子节点列表
        List<BrokerMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (BrokerMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<BrokerMenu> getChildList(List<BrokerMenu> list, BrokerMenu t) {
        return StreamUtils.filter(list, n -> n.getParentId().equals(t.getMenuId()));
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<BrokerMenu> list, BrokerMenu t) {
        return CollUtil.isNotEmpty(getChildList(list, t));
    }

    /**
     * 内链域名特殊字符替换
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS, Constants.WWW, ".", ":"},
            new String[]{"", "", "", "/", "/"});
    }
}
